package ru.cod.rs.exmpls.main.interfaces.impl;

import java.io.IOException;

import ru.cod.rs.exmpls.main.interfaces.Audio;
import ru.cod.rs.exmpls.main.interfaces.Music;
import ru.cod.rs.exmpls.main.interfaces.Sound;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;

public class AudioImpl implements Audio {

	AssetManager assetManager;
	SoundPool soundPool;

	public AudioImpl(Activity activity) {
		activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		assetManager = activity.getAssets();
		soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
	}

	@Override
	public Music newMusic(String fname) {
		try {
			AssetFileDescriptor aDescr = assetManager.openFd(fname);
			return new MusicImpl(aDescr);
		} catch (IOException e) {
			throw new RuntimeException("Couldn't load music '" + fname + "'");
		}
	}

	@Override
	public Sound newSound(String fname) {
		try {
			AssetFileDescriptor asDescr = assetManager.openFd(fname);
			int soundId = soundPool.load(asDescr, 0);
			return new SoundImpl(soundPool, soundId);
		} catch (IOException e) {
			throw new RuntimeException("Couldn't load sound '" + fname + "'");
		}
	}
}
